﻿import base64
import hashlib 
import hmac 
import json 
import time 
import logging 
import requests
import mysql.connector
import datetime


class gdt():
	"""docstring for ClassName"""

	def getGdt(self,token,secret,qudao):

		endCallTime=datetime.datetime.now().strftime('%Y-%m-%d');

		startCallTime=(datetime.datetime.now()-datetime.timedelta(hours=24)).strftime('%Y-%m-%d')

		print(startCallTime)

		# startCallTime="2020-07-17";

		# endCallTime="2020-07-23";

		#token='171887411595049713';   #广告主线索平台token
		
		#secret='ceabc0d2cc630c37be55c6cb23b4161b';    #广告主线索平台生成的接口密钥
		
		timestamp=str(int(time.time()));   #即当前的秒级时间戳
		
		str1=token + "," + timestamp + ","  + self.get_str_sha1_secret_str(token + "." + timestamp + "." + secret);
		
		signature=base64.b64encode(str1.encode('utf-8'));			
		
		url='http://leads.qq.com/api/mv1/leads/list';
		
		params={'start_time':startCallTime,'end_time':endCallTime,'page':1,'page_size':200};
		
		headers={'X-Signature':signature,'Accept':'application/json'};
		
		resp = requests.get(url=url, params=params, headers=headers);

		dat=json.loads(resp.text)['data']['list'];

		print('广点通更新：'+str(self.upDb(dat,'gdtphone',qudao)));

	def get_str_sha1_secret_str(self,res:str):
	    """
	    使用sha1加密算法，返回str加密后的字符串
	    """
	    sha = hashlib.sha1(res.encode('utf-8'))
	    encrypts = sha.hexdigest()

	    return encrypts

	def upDb(self,dataa,table,qudao):

		mydb = mysql.connector.connect(
		  host="localhost",       # 数据库主机地址
		  user="root",    # 数据库用户名
		  passwd="root",   # 数据库密码
		  database="weizandata"
		)

		mycursor = mydb.cursor()
		upCount=0
		for item in dataa:

			val=[]
			filed=[]
			for key in item:
				filed.append(key)
				val.append('\''+str(item[''+key+''])+'\'')

			filedStr=','.join(filed)
			valStr=','.join(val)
			sql="INSERT IGNORE INTO "+table+" ("+filedStr+",qudao)value("+valStr+",'"+qudao+"');"
			#print(sql+'\n')
			mycursor.execute(sql)
			mydb.commit()
			upCount=upCount+int(mycursor.rowcount)
		return upCount

if __name__ == '__main__':

	gd=gdt();
	gd.getGdt('171764841595465948','928d32ea9b68307bc947089315edb8d1','1122785705056145408');#优居朋友圈
	#gd.getGdt('171887411595049713','ceabc0d2cc630c37be55c6cb23b4161b','1284016882717954048');#广电通
